package pers.cj.pdos.excel;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import pers.cj.pdos.constant.OrderType;

import pers.cj.pdos.entity.*;
import pers.cj.pdos.service.IOrderRuleService;
import pers.cj.pdos.service.IProviderService;
import pers.cj.pdos.service.IProviderTypeService;
import pers.cj.pdos.utils.DataUtil;
import pers.cj.pdos.utils.DateUtils;
import pers.cj.pdos.utils.Logger;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.DataMsg;
import pers.cj.pdos.vo.ProviderVo;

import java.util.*;

public class ExcelProviderListener extends AnalysisEventListener<ExcelProvider> {
    /**
     * 系统存在的数据-从数据库读取
     */
    private Company company;//所属公司

    private Map<String,String> sysProviderTypeMap;//分类 key-名称  value-id

    private Map<String,String> sysNoMap;//编号 key-no  value-""

    private Map<String,String> sysNameMap;//名称 key-name  value-""

    private String defaultProviderTypeId;
    //---------------------------------------------------------------------------------

    /**
     * 导入失败的客户
     */
    private List<DataMsg> dataMsgList=new ArrayList<>();

    /**
     * 需要新增的数据
     */
    private List<ProviderType> providerTypeList=new ArrayList<>();

    private List<Provider> providerList=new ArrayList<>();

    private final String YYYYMMDD = DateUtils.getDate(new Date(), DateUtils.YYYYMMDD);

    OrderRule orderRule;
    IOrderRuleService orderRuleService;
    private String storeId;
    public void init(Company company, User user){
        storeId=user.getStoreId();
        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        orderRuleService = (IOrderRuleService)context.getBean("orderRuleServiceImpl");
        IProviderTypeService providerTypeService = (IProviderTypeService)context.getBean("providerTypeServiceImpl");
        IProviderService providerService = (IProviderService)context.getBean("providerServiceImpl");


        orderRule = orderRuleService.getByType(company.getId(), OrderType.GYS.getType());
        long time = System.currentTimeMillis();
        Logger.getLogger(getClass()).info("-----------------------------------------------------初始化开始----------------------------------------------");

        this.company = company;

        //处理分类
        String defaultProviderTypeId = null;
        Map<String,String> sysProviderTypeMap = new HashMap<>();
        for (ProviderType providerType : providerTypeService.listPage(null,null, company.getId())) {
            if (defaultProviderTypeId == null){
                defaultProviderTypeId = providerType.getId();
            }
            sysProviderTypeMap.put(providerType.getName(),providerType.getId());
        }
        this.defaultProviderTypeId = defaultProviderTypeId;
        this.sysProviderTypeMap = sysProviderTypeMap;

        //处理编码
        Map<String,String> sysNoMap = new HashMap<>();
        Map<String,String> sysNameMap = new HashMap<>();
        for (ProviderVo providerVo : providerService.listVo(company.getId())) {
            sysNoMap.put(providerVo.getNo(), "");
            sysNameMap.put(providerVo.getName(), "");
        }
        this.sysNoMap = sysNoMap;
        this.sysNameMap = sysNameMap;


        System.out.println("company:"+company);
        System.out.println("sysProviderTypeMap:"+sysProviderTypeMap);
        System.out.println("defaultProviderTypeId:"+defaultProviderTypeId);
        System.out.println("sysNoMap:"+sysNoMap);
        System.out.println("sysNoMap:"+sysNoMap);
        Logger.getLogger(getClass()).info("-----------------------------------------------------初始化结束,所耗费的时间:"+(System.currentTimeMillis()-time)+"----------------------------------------------");
    }

    @Override
    public void invoke(ExcelProvider excelProvider, AnalysisContext analysisContext) {
        process(excelProvider);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        orderRuleService.updateById(orderRule);
    }

    private DataMsg genDataMsg(ExcelProvider excel,String msg) {
        Custom custom = new Custom();
        custom.setNo(Utils.isEmpty(excel.getNo()) ? "未填写":excel.getNo());
        custom.setName(Utils.isEmpty(excel.getName()) ? "未填写":excel.getName());
        DataMsg goodsMsg = new DataMsg();
        goodsMsg.setData(custom);
        goodsMsg.setMsg(msg);
        return goodsMsg;
    }

    /**
     <li>1.“供应商名称”名称为必填项，若未填写，则舍弃</li>
     <li>2.如您填写的“供应商名称”重复，则舍弃</li>
     <li>3.如您填写的“供应商编号”重复，则舍弃</li>
     <li>4.如您填写的“供应商名称”或“供应商编号”与系统内的不重复，但表格内数据有重复，则会取第一条数据</li>
     <li>5.“分类”一栏若未填写，则会自动默认值</li>
     <li>6.“供应商编号”一栏若未填写，系统会自动生成</li>
     *
     * @param excel
     */
    void process(ExcelProvider excel){
        //检查操作
        if (Utils.isEmpty(excel.getName())){
            Logger.getLogger(ExcelProviderListener.class).info("名称为空,舍弃该数据");
            dataMsgList.add(genDataMsg(excel,"名称为空"));
            return;
        }

        if (sysNoMap.containsKey(excel.getNo())) {
            Logger.getLogger(ExcelProviderListener.class).info("编号【"+excel.getNo()+"】重复,舍弃该数据");
            dataMsgList.add(genDataMsg(excel,"编号【"+excel.getNo()+"】系统已存在"));
            return;
        }

        if (sysNameMap.containsKey(excel.getName())) {
            Logger.getLogger(ExcelProviderListener.class).info("名称重复【"+excel.getName()+"】重复,舍弃该数据");
            dataMsgList.add(genDataMsg(excel,"名称【"+excel.getName()+"】系统已存在"));
            return;
        }

        if (Utils.isEmpty(excel.getType()) && Utils.isEmpty(defaultProviderTypeId)) {
            //如果没有商品分类，且系统没有商品分类，则舍弃该商品
            Logger.getLogger(ExcelProviderListener.class).info("未填写分类，且系统中没有分类,舍弃该数据");
            dataMsgList.add(genDataMsg(excel,"未填写分类，且系统中还未设置分类"));
            return;
        }


        Provider provider = new Provider();
        DataUtil.processEntity(company,provider);

        //未填写分类
        if (Utils.isEmpty(excel.getType())){
            provider.setProviderTypeId(defaultProviderTypeId);
        } else {
            if (sysProviderTypeMap.containsKey(excel.getType())) {
                provider.setProviderTypeId(sysProviderTypeMap.get(excel.getType()));
            } else {
                //系统中没有该分类，则需新增
                ProviderType type = new ProviderType();
                DataUtil.processEntity(company,type);
                type.setName(excel.getType());
                providerTypeList.add(type);
                provider.setProviderTypeId(type.getId());
                //系统map中加入新增的type
                sysProviderTypeMap.put(type.getName(),type.getId());
            }
        }

        if (Utils.isLetterDigit(excel.getNo())) {
            provider.setNo(excel.getNo());
        }else {
            //编号不是数字字母，系统生成对应的商品编号
            provider.setNo(getNo());
            System.out.println("编号不是数字字母，系统生成对应的商品编号：" + excel.getNo());
        }

        provider.setName(excel.getName());
        provider.setDef(false);
        provider.setRemark(excel.getRemark());
        provider.setContacts(excel.getContacts());
        provider.setPhone(excel.getPhone());
        provider.setUnitTel(excel.getUnitTel());
        provider.setAddress(excel.getAddress());
        provider.setCode(excel.getCode());
        provider.setEmail(excel.getEmail());
        provider.setTax(excel.getTax());
        provider.setWechat(excel.getWechat());
        provider.setQq(excel.getQq());
        provider.setStatus("停用".equals(excel.getStatus()) ? 2 : 1);
        provider.setStoreId(storeId);

        providerList.add(provider);
        sysNoMap.put(provider.getNo(),"");
        sysNameMap.put(provider.getName(),"");

    }

    private String getNo(){
        StringBuilder sb = new StringBuilder();
        sb.append(orderRule.getPrefix());
        sb.append(YYYYMMDD);
        sb.append(String.format("%0"+orderRule.getNum()+"d",orderRule.getCurrent()));
        orderRule.setCurrent(orderRule.getCurrent()+1);
        return sb.toString();
    }

    public List<DataMsg> getDataMsgList() {
        return dataMsgList;
    }

    public List<ProviderType> getProviderTypeList() {
        return providerTypeList;
    }

    public List<Provider> getProviderList() {
        return providerList;
    }
}
